import java.util.Random;
abstract class RedEnvelope {
    public double remainMoney;    //红包当前金额
    public int remainPeople;      //当前参与抢红包的人数  
    public double money ;         //当前用户抢到的金额
    public abstract double giveMoney(); //抽象方法，具体怎么抢红包由子类完成
}
class RandomRedEnvelope extends RedEnvelope { 
    double minMoney;       
    int integerRemainMoney;
    int randomMoney;          
    Random random;
    RandomRedEnvelope(double remainMoney,int remainPeople) {
       random = new Random();
       minMoney = 0.01;  
       this.remainMoney =  remainMoney;
       this.remainPeople = remainPeople;
       integerRemainMoney =(int)(remainMoney*100); 
       if(integerRemainMoney<remainPeople*(int)(minMoney*100)){
          integerRemainMoney = remainPeople*(int)(minMoney*100);
          this.remainMoney =(double)integerRemainMoney;
       }
    }
    public double giveMoney() {
      if(remainPeople<=0) {
         return 0;
      }
      if(remainPeople ==1) {
         money = remainMoney;
         remainPeople--;
         return money;
      }
      randomMoney = random.nextInt(integerRemainMoney);
      if(randomMoney<(int)(minMoney*100)) {
         randomMoney = (int)(minMoney*100);    
      }
      int leftOtherPeopleMoney =integerRemainMoney-randomMoney;
      int otherPeopleNeedMoney = (remainPeople-1)*(int)(minMoney*100);
      if(leftOtherPeopleMoney<otherPeopleNeedMoney) {
        randomMoney -=(otherPeopleNeedMoney-leftOtherPeopleMoney);
      }
      integerRemainMoney = integerRemainMoney - randomMoney;
      remainMoney = (double)(integerRemainMoney/100.0); 
      remainPeople--;
      money = (double)(randomMoney/100.0);
      return money;  
   }
}
public class Example8_23 {
   public static void main(String args[]) {
      RedEnvelope redEnvelope = new RandomRedEnvelope(5.20,6);
      System.out.printf("以下用循环输出%d个人抢%.2f圆的随机红包:\n",
                         redEnvelope.remainPeople,redEnvelope.remainMoney);
      showProcess(redEnvelope);
   }
   public static void showProcess (RedEnvelope redEnvelope) {
      double sum = 0;
      while(redEnvelope.remainPeople>0){
         double money = redEnvelope.giveMoney();
         System.out.printf("%.2f\t",money);
         sum = sum+money;
      }
      String s = String.format("%.2f",sum); 
      sum = Double.parseDouble(s);
      System.out.printf("\n%.2f圆的红包被抢完",sum);
   }
}
